package com.yamaikeji.plan.aop;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yamaikeji.common.core.domain.AjaxResult;
import com.yamaikeji.common.utils.StringUtils;
import com.yamaikeji.framework.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


@Aspect
@Component
public class CheckLoginAspect {

    private static final Logger log = LoggerFactory.getLogger(CheckLoginAspect.class);

    @Resource
    private RedisUtil redisUtil;

    @Pointcut("@annotation(com.yamaikeji.plan.aop.CheckLogin)")
    private void cutMethod() {

    }

    /**
     * 前置通知：在目标方法执行前调用
     */
    @Before("cutMethod()")
    public void begin() throws JsonProcessingException {

    }

    /**
     * 后置通知：在目标方法执行后调用，若目标方法出现异常，则不执行
     */
    @AfterReturning("cutMethod()")
    public void afterReturning() {

    }

    /**
     * 后置/最终通知：无论目标方法在执行过程中出现一场都会在它之后调用
     */
    @After("cutMethod()")
    public void after() {

    }

    /**
     * 异常通知：目标方法抛出异常时执行
     */
    @AfterThrowing("cutMethod()")
    public void afterThrowing() {

    }

    /**
     * 环绕通知：灵活自由的在目标方法中切入代码
     */
    @Around("cutMethod()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        HttpServletResponse response = attributes.getResponse();
        // 获取请求参数并转换为json格式
        if ("POST".equalsIgnoreCase(request.getMethod())) {
            Object[] args = joinPoint.getArgs();
            List<Object> argsList = Arrays.asList(args).stream()
                    .filter(arg -> (!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) && !(arg instanceof MultipartFile) && !(arg instanceof MultipartFile[])))
                    .collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(argsList)) {
                String params = JSON.toJSONString(argsList.get(0));
                log.info("请求参数:{}", params);
            }
        }
        String token = request.getHeader("token");
        log.info("token:{}", token);
        long beginTime = System.currentTimeMillis();
        String userNo = (String) redisUtil.get(token);
        log.info("useTime用时:{}", System.currentTimeMillis() - beginTime);
        if (StringUtils.isEmpty(userNo)) {
            AjaxResult ajaxResult = AjaxResult.error("非法访问");
            errorResponse(response, ajaxResult);
        }
        request.setAttribute("userNo", userNo);
        return joinPoint.proceed();
    }

    //返回错误提示
    public void errorResponse(HttpServletResponse resp, AjaxResult ajaxResult) throws IOException, UnsupportedEncodingException {
        OutputStream out = null;
        try{
            resp.setCharacterEncoding("utf-8");
            resp.setContentType("text/json");
            out = resp.getOutputStream();
            out.write(JSON.toJSONString(ajaxResult).getBytes("utf-8"));
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally{
            if(out!=null){
                out.close();
            }
        }
    }

    /**
     * 获取方法中声明的注解
     *
     * @param joinPoint
     * @return
     * @throws NoSuchMethodException
     */
    public CheckLogin getDeclaredAnnotation(ProceedingJoinPoint joinPoint) throws NoSuchMethodException {
        // 获取方法名
        String methodName = joinPoint.getSignature().getName();
        // 反射获取目标类
        Class<?> targetClass = joinPoint.getTarget().getClass();
        // 拿到方法对应的参数类型
        Class<?>[] parameterTypes = ((MethodSignature) joinPoint.getSignature()).getParameterTypes();
        // 根据类、方法、参数类型（重载）获取到方法的具体信息
        Method objMethod = targetClass.getMethod(methodName, parameterTypes);
        // 拿到方法定义的注解信息
        CheckLogin annotation = objMethod.getDeclaredAnnotation(CheckLogin.class);
        // 返回
        return annotation;
    }
}

